<!DOCTYPE html>
<html lang="zh-cn">
	<head>
		<meta charset="UTF-8">
		<title class="title">canvasDemo</title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}

			.box {
				width: 300px;
				margin: auto;
			}

			#canvas {
				border: 1px solid black;
			}
		</style>
	</head>
	<script type="text/javascript">
		let canWidth = 300;
		let canhidth = 300;
		function ball(x, y) { //小球对象
			this.x = x; //起始x轴坐标
			this.y = y; //起始y轴坐标
			this.r = Math.floor(Math.random() * (40 - 10 + 1) + 10);//随机生成半径
			this.color = '#' + Math.random().toString(16).substr(2, 6); //随机生成颜色
			this.runX = Math.floor(Math.random() * (6 - 2 + 1) + 2); //X轴移动坐标
			this.runY = Math.floor(Math.random() * (6 - 2 + 1) + 2); //y轴移动坐标
			this.ballCan = function(ctx) { //在画布上创建
				ctx.beginPath();//开始新路径
				ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, true);//再画布上画一个小球
				ctx.fillStyle = this.color//赋予颜色
				ctx.fill();//结束绘制
			};
			this.ballRun = function(ctx) {
				if (this.x + this.r <= 0 || this.x - this.r/2  >= canWidth ) {//x轴到边回弹
					this.runX = -this.runX
				}
				this.x += this.runX
				if (this.y + this.r <= 0 || this.y - this.r/2 >= canhidth) {//y轴到边回弹
					this.runY = -this.runY
				}
				this.y += this.runY
				this.ballCan(ctx)
			}
		}

		function draw() {
			let canvas = document.querySelector("#canvas")
			if (canvas.getContext) {
				var ctx = canvas.getContext('2d');
				let b1 = new ball(10, 10)
				let b2 = new ball(10, 30)
				let b3 = new ball(10, 10)
				let b4 = new ball(50, 10)
				let b5 = new ball(10, 40)
				let b6 = new ball(100, 10)
				let b7 = new ball(200, 40)
				setInterval(() => {
					ctx.clearRect(0, 0, canWidth, canWidth);//清空画布
					b1.ballRun(ctx)
					b2.ballRun(ctx)
					b3.ballRun(ctx)
					b4.ballRun(ctx)
					b5.ballRun(ctx)
					b6.ballRun(ctx)
					b7.ballRun(ctx)
				}, 10)
			}
		}
	</script>
	<body onload="draw();">
		<div class="box">
			<canvas id="canvas" height="300" width="300">

			</canvas>
		</div>
	</body>

</html>
